package AdminService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/tools"
	"github.com/gogf/gf/os/gcache"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"time"
)

// GetPermsByAdminId 按 adminid 获取角色及角色下的权限
func GetPermsByAdminId(ctx context.Context, adminId int) ([]string, error) {
	cacheDuration := g.Cfg().GetDuration("site.AdminCacheTimeout") * time.Second
	/*
		dbPrefix := g.Cfg().GetString("database.prefix")
		// 取出 权限
		var permsRes []gdb.Value
		permsRes, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
			"srm.menu_id = sm.id").Where(
			"sm.type = 2 AND srm.role_id IN (SELECT role_id FROM "+dbPrefix+"admin_role WHERE admin_id = ?)",
			adminId).Fields("sm.perms").Cache(cacheDuration,
			"adminCache:perms:"+gconv.String(adminId),
		).Array()
		if err != nil {
			return nil, err
		}
		// 整理权限列表
		permsTmp := gconv.SliceStr(permsRes)
		var perms []string
		for _, item := range permsTmp {
			if strings.Index(item, ",") > -1 {
				perms = append(perms, strings.Split(item, ",")...)
			} else {
				perms = append(perms, item)
			}
		}
	*/

	// 直接存入本地缓存
	val, err := gcache.New().GetOrSetFunc("adminCache:perms:"+gconv.String(adminId), func() (interface{}, error) {
		dbPrefix := g.Cfg().GetString("database.prefix")
		// 取出 权限
		var permsRes []gdb.Value
		permsRes, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
			"srm.menu_id = sm.id").Where(
			"sm.type = 2 AND srm.role_id IN (SELECT role_id FROM "+dbPrefix+"admin_role WHERE admin_id = ?)",
			adminId).Fields("sm.perms").Array()
		if err != nil {
			return nil, err
		}
		// 整理权限列表
		permsTmp := gconv.SliceStr(permsRes)
		var perms []string
		for _, item := range permsTmp {
			if strings.Index(item, ",") > -1 {
				perms = append(perms, strings.Split(item, ",")...)
			} else {
				perms = append(perms, item)
			}
		}

		return tools.RemoveDuplicatesAndEmpty(perms), nil
	}, cacheDuration)

	if err != nil {
		return nil, err
	}

	return val.([]string), nil
}
